const ManagementTagsProxy = require('../proxy/management-tags')
const removeTagByIdFromTeam = require('../proxy/teams').removeTagById

exports.calculateManagement = async function(tags) {
  const management = {
    contrast: false,
    dormitory: false,
    bursary: false,
    evaluation: false,
    party: false,
    registry: false,
    vote: false,
    resource: false,
    announcement: false
  }
  if (!tags.length) {
    await tags.reduce(async(total, current) => {
      const res = await ManagementTagsProxy.fetchById(current)
      // calculate management
      for (const key in management) {
        total[key] = total[key] || res[key]
      }
      return total
    }, management)
  }
  return management
}

exports.addUserById = function(tagId, userId) {
  return ManagementTagsProxy.addUserById(tagId, userId)
}

exports.removeUserById = function(tagId, userId) {
  return ManagementTagsProxy.removeUserById(tagId, userId)
}

exports.createTagWithName = function(name) {
  return ManagementTagsProxy.createWithName(name)
}

exports.updatePowerById = function(tagId, newTag) {
  const { name, announcement, resource, vote, registry, party, evaluation, dormitory, bursary, contrast } = newTag
  const update = { name, announcement, resource, vote, registry, party, evaluation, dormitory, bursary, contrast }
  return ManagementTagsProxy.updateById(tagId, update)
}

exports.findById = function(tagId) {
  return ManagementTagsProxy.findById(tagId)
}

exports.removeTagInTeam = async function(teamId, tagId) {
  try {
    const tag = await ManagementTagsProxy.fetchById(tagId)
    if (tag.members.length) {
      return false
    } else {
      await ManagementTagsProxy.deleteById(tagId)
      await removeTagByIdFromTeam(teamId, tagId)
      return true
    }
  } catch (err) {
    throw err
  }
}

exports.updateAllMembersManagementInTag = function(tagId) {
  ManagementTagsProxy.fetchAllMembersManagementTagsInTag(tagId).exec(function(err, management_tag) {
    if (err) {
      console.log('[ERROR]')
      console.log(err)
    } else {
      const managementKeys = ['contrast', 'dormitory', 'bursary', 'evaluation', 'party', 'registry', 'vote', 'resource', 'announcement']
      for (const item of management_tag.members) {
        // update each user's management
        // calculate new management
        const newManagement = item.teams[0].management_tags.reduce((total, current) => {
          for (const k of managementKeys) {
            total[k] = total[k] || current[k]
          }
          return total
        }, {})
        // set and save newManagement in user
        item.teams[0].management = newManagement
        item.save()
      }
    }
  })
}
